<?php
namespace Common\Model;
use Think\Model;
/**
 * 用户Model
 */
class UserModel extends Model
{
  private $_db = '';
  public function __construct(){
    $this->_db = M('user');
  }
  public function addNewUser($info){
    $map['status'] = 0;
    $map['create_time'] = time();
    return $this->_db->add($info);
  }
  public function getUserCount($map = array()){
      $map['status'] = array('neq',-1);
      return $this->_db->where($map)->count();
  }
  public function getUserList($page,$pageSize){
    $map['status'] = array('neq',-1);
    $offset = ($page-1)*$pageSize;
    return $this->_db->where($map)->order('user_id')->limit($offset,$pageSize)->select();
  }
  public function getUserById($id){
    $map['user_id']  = $id;
    $map['status'] = array('neq',-1);
    return $this->_db->where($map)->find();
  }
  public function UserLogin($username,$password){
    $map['username'] = $username;
    $map['status'] = array('neq',-1);
    $user = $this->_db->where($map)->find();
    if(getAdminPwd($password) == $user['password']&&is_array($user)){
      session('user',$user);
      return true;
    }else{
      return false;
    }
  }
  public function updateUser($id,$data){
    if(!$id||!is_numeric($id)){
      throw_exception("ID不合法");
    }
    if(!$data||!is_array($data)){
      throw_exception("数据不合法");
    }
    $map['password'] = getAdminPwd($data['password']);
    $map['user_id'] = $id;
    return $this->_db->where($map)->save($data);
  }
  public function register($data){
    $info['username'] = $data['username'];
    $info['password'] = getAdminPwd($data['password']);
    $info['email'] = $data['email'];
    $info['status'] = 0;
    $info['create_time'] = time();
    if($this->checkUserExist($info['username'])){
      return false;
    }
    $res = $this->_db->add($info);
    return $res;
  }
  public function checkUserExist($username){
    $map['username'] = $username;
    $res = $this->_db->where($map)->find();
    if($res){
      return true;
    }else{
      return false;
    }
  }

}
